/**
 * 获取目前所有的任务
 */

const LOCAL_KEY = "todomvc";

export function fetch() {
  const result = localStorage.getItem(LOCAL_KEY);
  if (result) {
    return JSON.parse(result); //JSON 字符串 → JavaScript 对象
  }
  return [];
}

/**
 *
 * @param {*} todos 任务列表
 */
export function save(todos) {
  localStorage.setItem(LOCAL_KEY, JSON.stringify(todos)); //JavaScript 对象 → JSON 字符串
}
/**
 * 生成任务的唯一编号:时间戳+4位随机数
 *
 */

export function generateId() {
  return Date.now() + Math.random().toString(16).substr(2, 4);
}

/**
 * 筛选todos
 */
export function filter(todos, visibility = "all") {
  if (visibility === "all") {
    return todos;
  } else if (visibility === "active") {
    return todos.filter((it) => !it.completed);
  } else if (visibility === "completed") {
    return todos.filter((it) => it.completed);
  }
  throw new Error("invalid visblity value");
}
